<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-tag"></i> {{ pageTitle }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.topicName" placeholder="话题名称" class="handle-input mr10" clearable />
        <!-- <el-select v-model="searchForm.isHot" placeholder="是否热门" class="handle-select mr10" clearable>
          <el-option label="全部" value="" />
          <el-option label="热门" :value="1" />
          <el-option label="普通" :value="0" />
        </el-select> -->
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showAddTopic">新增话题</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="topicTable" header-cell-class-name="table-header">
        <el-table-column prop="topicId" label="话题ID" width="100" />
        <el-table-column prop="topicName" label="话题名称" />
        <el-table-column prop="isHot" label="是否热门" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isHot ? 'danger' : 'info'">
              {{ scope.row.isHot ? '热门' : '普通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="noteCount" label="关联笔记数" align="center" />
        <el-table-column prop="topicPopularity" label="话题热度" align="center" sortable />
        <el-table-column prop="topicDescription" label="话题描述" min-width="200">
          <template #default="scope">
            <div class="description-cell">
              {{ scope.row.topicDescription || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ scope.row.updateTime ? dateFormat(scope.row.updateTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditTopic(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑话题弹窗 -->
    <el-dialog v-model="topicDialog.visible" :title="topicDialog.isEdit ? '编辑话题' : '新增话题'" width="500px">
      <el-form :model="topicDialog.form" :rules="topicRules" ref="topicForm" label-width="100px">
        <el-form-item label="话题名称" prop="topicName">
          <el-input v-model="topicDialog.form.topicName" placeholder="请输入话题名称" />
        </el-form-item>
        <el-form-item label="话题描述" prop="topicDescription">
          <el-input v-model="topicDialog.form.topicDescription" type="textarea" :rows="3" placeholder="请输入话题描述" />
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-radio-group v-model="topicDialog.form.isHot">
            <el-radio :label="0">普通话题</el-radio>
            <el-radio :label="1">热门话题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="话题热度" prop="topicPopularity">
          <el-input-number v-model="topicDialog.form.topicPopularity" :min="0" :max="999999" placeholder="话题热度值"
            style="width: 100%" />
          <div class="form-tip">热度值用于排序和筛选，数值越大排序越靠前</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="topicDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveTopic">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  getTopics, addTopic, updateTopic, deleteTopic,
  getForumTopics, addForumTopic, updateForumTopic, deleteForumTopic
} from "@/api/content";

export default {
  name: "TopicManagement",
  data() {
    return {
      searchForm: {
        topicName: "",
        isHot: "",
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 话题弹窗
      topicDialog: {
        visible: false,
        isEdit: false,
        editId: null,
        form: {
          topicName: "",
          topicDescription: "",
          isHot: 0,
          topicPopularity: 0,
        },
      },
      // 表单验证规则
      topicRules: {
        topicName: [
          { required: true, message: '请输入话题名称', trigger: 'blur' },
          { min: 1, max: 50, message: '话题名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        topicDescription: [
          { max: 200, message: '话题描述不能超过200个字符', trigger: 'blur' }
        ],
        isHot: [
          { required: true, message: '请选择是否为热门话题', trigger: 'change' }
        ],
        topicPopularity: [
          { required: true, message: '请输入话题热度', trigger: 'blur' },
          { type: 'number', min: 0, message: '话题热度不能小于0', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    pageTitle() {
      return this.isForumTopic ? '帖子话题管理' : '动态话题管理';
    },
    isForumTopic() {
      return this.$route.path === '/forumTopic';
    }
  },
  mounted() {
    this.getData();
  },
  watch: {
    '$route'() {
      // 路由切换时重置页面
      this.resetPage();
      this.getData();
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.topicName) {
        params.topicName = this.searchForm.topicName;
      }
      if (this.searchForm.isHot !== "") {
        params.isHot = this.searchForm.isHot;
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const apiMethod = this.isForumTopic ? getForumTopics : getTopics;
        const response = await apiMethod(params);

        if (response && response.data) {
          this.tableData = response.data.rows || response.data;

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取话题数据失败:', error);
        this.$message.error('获取话题数据失败');
      }
    },
    resetPage() {
      // 重置搜索表单
      this.searchForm = {
        topicName: "",
        isHot: "",
      };
      // 重置分页
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0
      };
      // 清空表格数据
      this.tableData = [];
      // 关闭弹窗
      this.topicDialog.visible = false;
    },
    showAddTopic() {
      this.topicDialog.visible = true;
      this.topicDialog.isEdit = false;
      this.topicDialog.editId = null;
      this.topicDialog.form = {
        topicName: "",
        topicDescription: "",
        isHot: 0,
        topicPopularity: 0,
      };
      this.$nextTick(() => {
        this.$refs.topicForm?.clearValidate();
      });
    },
    showEditTopic(row) {
      this.topicDialog.visible = true;
      this.topicDialog.isEdit = true;
      this.topicDialog.editId = row.topicId;
      this.topicDialog.form = {
        topicName: row.topicName || "",
        topicDescription: row.topicDescription || "",
        isHot: row.isHot || 0,
        topicPopularity: row.topicPopularity || 0,
      };
      this.$nextTick(() => {
        this.$refs.topicForm?.clearValidate();
      });
    },
    saveTopic() {
      this.$refs.topicForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              ...this.topicDialog.form
            };

            if (this.topicDialog.isEdit) {
              params.topicId = this.topicDialog.editId;
              const updateMethod = this.isForumTopic ? updateForumTopic : updateTopic;
              await updateMethod(params);
              this.$message.success('编辑话题成功');
            } else {
              const addMethod = this.isForumTopic ? addForumTopic : addTopic;
              await addMethod(params);
              this.$message.success('新增话题成功');
            }

            this.topicDialog.visible = false;
            this.getData();
          } catch (error) {
            console.error('保存话题失败:', error);
            this.$message.error('保存话题失败');
          }
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确定要删除话题"${row.topicName}"吗？`, "提示", {
        type: "warning"
      }).then(async () => {
        try {
          const deleteMethod = this.isForumTopic ? deleteForumTopic : deleteTopic;
          await deleteMethod({ topicId: row.topicId });
          this.$message.success('删除话题成功');
          this.getData();
        } catch (error) {
          console.error('删除话题失败:', error);
          this.$message.error('删除话题失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.description-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
</style>